package com.ai.imagetext.controller;

import com.ai.imagetext.dto.AIRecognitionResult;
import com.ai.imagetext.dto.AiAnalysisResponse;
import com.ai.imagetext.dto.TextContentDTO;
import com.ai.imagetext.entity.TextContent;
import com.ai.imagetext.entity.Image;
import com.ai.imagetext.repository.TextContentRepository;
import com.ai.imagetext.repository.ImageRepository;
import com.ai.imagetext.service.*;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/ai")
@RequiredArgsConstructor
public class AIController {

    private final AIService aiService;
    private final AIRecognitionService aiRecognitionService;
    private final OperationLogService operationLogService;
    private final TextGenService textGenService;
    private final TextContentRepository textContentRepository;
    private final ImageRepository imageRepository;
    private final ImageService imageService;

    /**
     * 图片分析生成文案接口
     * @author wangguiyou
     * @param image 上传的图片文件
     * @param customPrompt 自定义提示词（可选）
     * @return 分析结果
     */
    @PostMapping("/analyze")
    public ResponseEntity<Map<String, Object>> analyzeImage(
            @RequestParam("image") MultipartFile image,
            @RequestParam(value = "prompt", required = false) String customPrompt) {

        log.info("Image analysis request, file size: {}, content type: {}",
                image.getSize(), image.getContentType());

        try {
            // 验证图片文件
            validateImageFile(image);

            // 设置默认提示词
            if (customPrompt == null || customPrompt.trim().isEmpty()) {
                customPrompt = "请根据图片生成两段营销文案，一段短句社交文案，一段长句营销文案";
            }

            // 调用AI分析服务
            AiAnalysisResponse result = textGenService.analyzeImage(image, customPrompt);

            Map<String, Object> response = createSuccessResponse("图片分析完成");
            response.put("data", result);
            response.put("prompt", customPrompt);

            return ResponseEntity.ok(response);

        } catch (IllegalArgumentException e) {
            log.warn("Image validation failed: {}", e.getMessage());
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        } catch (Exception e) {
            log.error("Image analysis failed", e);

            // 针对不同类型的错误提供更友好的错误信息
            String errorMessage = getDetailedErrorMessage(e);

            // 如果是限流错误，返回503状态码，建议客户端重试
            if (isThrottlingError(e)) {
                return ResponseEntity.status(503).body(createErrorResponse(errorMessage));
            }

            return ResponseEntity.internalServerError().body(createErrorResponse(errorMessage));
        }
    }

    /**
     * 验证上传的图片文件
     * @author wangguiyou
     * @param image 图片文件
     * @throws IllegalArgumentException 验证失败时抛出异常
     */
    private void validateImageFile(MultipartFile image) {
        if (image.isEmpty()) {
            throw new IllegalArgumentException("请上传图片文件");
        }

        // 检查文件类型
        String contentType = image.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new IllegalArgumentException("只支持图片文件");
        }

        // 检查文件大小 (限制为5MB)
        if (image.getSize() > 5 * 1024 * 1024) {
            throw new IllegalArgumentException("图片文件不能超过5MB");
        }

        log.debug("Image file validation passed: {}, size: {} bytes",
                image.getOriginalFilename(), image.getSize());
    }

    /**
     * 基于图片ID生成文案接口（与 /text/generate 接口功能类似）
     * @author wangguiyou
     * @param request 图片分析请求
     * @return 分析结果
     */
    @PostMapping("/analyze/image")
    public ResponseEntity<Map<String, Object>> analyzeImageById(@RequestBody ImageAnalysisRequest request) {
        log.info("Image analysis by ID request for image: {}, prompt: {}",
                request.getImageId(), request.getCustomPrompt());

        try {
            // 设置默认提示词
            String prompt = request.getCustomPrompt();
            if (prompt == null || prompt.trim().isEmpty()) {
                prompt = "请根据图片生成两段营销文案，一段短句社交文案，一段长句营销文案";
            }

            // 这里可以调用相应的服务来处理基于图片ID的分析
            // 暂时返回成功响应，具体实现可以根据需要添加
            Map<String, Object> response = createSuccessResponse("图片分析任务已启动");
            response.put("imageId", request.getImageId());
            response.put("prompt", prompt);
            response.put("message", "图片分析正在进行中，请稍后查看结果");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Image analysis by ID failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 触发AI图片识别（前端调用的接口）
     * @author wangguiyou
     * @param imageId 图片ID
     * @return 识别结果
     */
    @PostMapping("/recognition/trigger/{imageId}")
    public ResponseEntity<Map<String, Object>> triggerRecognition(@PathVariable Long imageId) {
        log.info("Trigger AI recognition request for image: {}", imageId);

        try {
            // 调用手动识别方法，它会处理图片查找和识别逻辑
            AIRecognitionResult result = aiRecognitionService.manualRecognizeImage(imageId);

            Map<String, Object> response = createSuccessResponse("AI识别完成");
            response.put("data", result);
            response.put("imageId", imageId);

            return ResponseEntity.ok(response);

        } catch (IllegalArgumentException e) {
            log.warn("Invalid image ID in trigger recognition: {}", e.getMessage());
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        } catch (Exception e) {
            log.error("Trigger AI recognition failed for image: {}", imageId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("AI识别服务暂时不可用，请稍后重试"));
        }
    }

    /**
     * 获取AI识别结果
     * @author wangguiyou
     * @param imageId 图片ID
     * @return 识别结果
     */
    @GetMapping("/recognition/result/{imageId}")
    public ResponseEntity<Map<String, Object>> getRecognitionResult(@PathVariable Long imageId) {
        log.info("Get AI recognition result for image: {}", imageId);

        try {
            AIRecognitionResult result = aiRecognitionService.manualRecognizeImage(imageId);

            Map<String, Object> response = createSuccessResponse("获取识别结果成功");
            response.put("data", result);
            response.put("imageId", imageId);

            return ResponseEntity.ok(response);

        } catch (IllegalArgumentException e) {
            log.warn("Image not found for getting result: {}", imageId);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        } catch (Exception e) {
            log.error("Get recognition result failed for image: {}", imageId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("获取识别结果失败，请稍后重试"));
        }
    }

    /**
     * 重试AI识别
     * @author wangguiyou
     * @param imageId 图片ID
     * @return 重试结果
     */
    @PostMapping("/recognition/retry/{imageId}")
    public ResponseEntity<Map<String, Object>> retryRecognition(@PathVariable Long imageId) {
        log.info("Retry AI recognition for image: {}", imageId);

        try {
            // 重新执行识别
            AIRecognitionResult result = aiRecognitionService.manualRecognizeImage(imageId);

            Map<String, Object> response = createSuccessResponse("重试识别完成");
            response.put("data", result);
            response.put("imageId", imageId);

            return ResponseEntity.ok(response);

        } catch (IllegalArgumentException e) {
            log.warn("Image not found for retry: {}", imageId);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        } catch (Exception e) {
            log.error("Retry recognition failed for image: {}", imageId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("重试识别失败，请稍后重试"));
        }
    }

    /**
     * 手动触发图片识别
     */
    @PostMapping("/recognize/{imageId}")
    public ResponseEntity<Map<String, Object>> recognizeImage(@PathVariable Long imageId) {
        log.info("Manual recognition request for image: {}", imageId);

        try {
            AIRecognitionResult result = aiRecognitionService.manualRecognizeImage(imageId);

            Map<String, Object> response = createSuccessResponse("图片识别完成");
            response.put("data", result);
            response.put("imageId", imageId);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Manual recognition failed for image: {}", imageId, e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 批量识别图片
     */
    @PostMapping("/recognize/batch")
    public ResponseEntity<Map<String, Object>> batchRecognizeImages(@RequestBody List<Long> imageIds) {
        log.info("Batch recognition request for {} images", imageIds.size());

        try {
            // 异步执行批量识别
            aiRecognitionService.batchRecognizeImages(imageIds);

            Map<String, Object> response = createSuccessResponse("批量识别任务已启动");
            response.put("imageIds", imageIds);
            response.put("count", imageIds.size());
            response.put("message", "识别任务正在后台执行，请稍后查看结果");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Batch recognition failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 重试失败的识别任务
     */
    @PostMapping("/recognize/retry-failed")
    public ResponseEntity<Map<String, Object>> retryFailedRecognitions() {
        log.info("Retry failed recognitions request");

        try {
            // 异步执行重试任务
            aiRecognitionService.retryFailedRecognitions();

            Map<String, Object> response = createSuccessResponse("重试任务已启动");
            response.put("message", "正在重新识别失败的图片，请稍后查看结果");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Retry failed recognitions failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 获取识别统计信息
     */
    @GetMapping("/recognition/statistics")
    public ResponseEntity<Map<String, Object>> getRecognitionStatistics() {
        log.info("Getting recognition statistics");

        try {
            AIRecognitionService.RecognitionStatistics stats = aiRecognitionService.getRecognitionStatistics();

            Map<String, Object> response = createSuccessResponse("获取识别统计信息成功");
            response.put("data", stats);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Get recognition statistics failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 获取AI服务状态
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getAIServiceStatus() {
        log.info("Getting AI service status");

        try {
            Map<String, Object> status = aiService.getServiceStatus();

            Map<String, Object> response = createSuccessResponse("获取AI服务状态成功");
            response.put("data", status);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Get AI service status failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 测试AI服务连接
     */
    @GetMapping("/test-connection")
    public ResponseEntity<Map<String, Object>> testAIConnection() {
        log.info("Testing AI service connection");

        try {
            boolean connected = aiService.testConnection();

            Map<String, Object> response = createSuccessResponse("AI服务连接测试完成");
            response.put("connected", connected);
            response.put("message", connected ? "连接正常" : "连接失败");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Test AI connection failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 测试文案生成服务
     * @author wangguiyou
     */
    @PostMapping("/test-text-generation")
    public ResponseEntity<Map<String, Object>> testTextGeneration(
            @RequestParam("imageUrl") String imageUrl,
            @RequestParam(value = "contentType", defaultValue = "SHORT") String contentType,
            @RequestParam(value = "styleType", defaultValue = "PROFESSIONAL") String styleType,
            @RequestParam(value = "customPrompt", required = false) String customPrompt) {

        log.info("Testing text generation service with imageUrl: {}", imageUrl);

        try {
            AIService.TextGenerationResult result = aiService.generateText(imageUrl, contentType, styleType, customPrompt);

            Map<String, Object> response = createSuccessResponse("文案生成测试完成");
            response.put("data", result);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Text generation failed", e);

            // 针对不同类型的错误提供更友好的错误信息
            String errorMessage = getDetailedErrorMessage(e);

            // 如果是限流错误，返回503状态码，建议客户端重试
            if (isThrottlingError(e)) {
                return ResponseEntity.status(503).body(createErrorResponse(errorMessage));
            }

            return ResponseEntity.badRequest().body(createErrorResponse(errorMessage));
        }
    }

    /**
     * 直接识别图片URL（用于测试）
     */
    @PostMapping("/recognize/url")
    public ResponseEntity<Map<String, Object>> recognizeImageUrl(@RequestBody Map<String, String> request) {
        String imageUrl = request.get("imageUrl");
        log.info("Direct recognition request for URL: {}", imageUrl);

        try {
            AIRecognitionResult result = aiService.recognizeImage(imageUrl);

            Map<String, Object> response = createSuccessResponse("图片URL识别完成");
            response.put("data", result);
            response.put("imageUrl", imageUrl);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Direct URL recognition failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }


    /**
     * 图生文接口 - 为图片生成文案
     * @author wangguiyou
     * @param request 文案生成请求
     * @return 生成结果
     */
    @PostMapping("/text/generate")
    public ResponseEntity<Map<String, Object>> generateText(@RequestBody TextGenerationRequest request) {
        log.info("Text generation request received - imageId: {}, contentType: {}, styleType: {}, customPrompt: {}",
                request.getImageId(), request.getContentType(), request.getStyleType(),
                request.getCustomPrompt() != null ? "[PROVIDED]" : "[EMPTY]");
        imageService.incrementUsageCount(request.getImageId());

        try {
            // 参数验证
            validateTextGenerationRequest(request);

            // 枚举类型转换
            TextContent.ContentType contentType = TextContent.ContentType.valueOf(request.getContentType().toUpperCase());
            TextContent.StyleType styleType = TextContent.StyleType.valueOf(request.getStyleType().toUpperCase());

            log.debug("Calling text generation service for image: {}", request.getImageId());

            // 构建文案生成提示词
            String prompt = request.getCustomPrompt();
            prompt += String.format("请为图片ID %d 生成%s风格的文案，文案长度为%s,一共生成五条并给出1,2,3进行标明,返回的格式为json的字符串数组形式",
                    request.getImageId(),
                    styleType.name().toLowerCase(),
                    contentType.name().toLowerCase());

            log.info("stryle:{},contenttype:{}",styleType.name().toLowerCase(),contentType.name().toLowerCase());
            Long imageId=request.getImageId();
            // 使用TextGenService生成文案
            String generatedText = textGenService.chatWithAi(imageId,prompt);

            // 检查是否是错误消息
            boolean isError = generatedText.startsWith("抱歉，AI服务暂时不可用") ||
                             generatedText.contains("错误信息:");

            // 保存文案到数据库
            TextContent textContent = new TextContent();

            // 获取图片实体
            Image image = imageRepository.findById(imageId)
                    .orElseThrow(() -> new IllegalArgumentException("图片不存在，ID: " + imageId));

            textContent.setImage(image);
            textContent.setUserId(image.getUserId()); // 从图片实体获取用户ID
            textContent.setContent(generatedText);
            textContent.setContentType(contentType);
            textContent.setStyleType(styleType);
            textContent.setPromptUsed(prompt);
            textContent.setAiGenerationStatus(isError ? TextContent.AIGenerationStatus.FAILED : TextContent.AIGenerationStatus.SUCCESS);
            textContent.setIsDeleted(false);

            // 保存到数据库
            TextContent savedTextContent = textContentRepository.save(textContent);

            // 创建用户操作日志数据
            long generatedId  = textContentRepository.findLatest().get().getId();
            operationLogService.recordImageToTextOperation(image.getUserId(),image.getId(),generatedId);


            Map<String, Object> textData = new HashMap<>();
            textData.put("id", savedTextContent.getId()); // 使用数据库生成的真实ID
            textData.put("imageId", request.getImageId());
            textData.put("content", generatedText);
            textData.put("contentType", request.getContentType());
            textData.put("styleType", request.getStyleType());
            textData.put("status", isError ? "ERROR" : "SUCCESS");
            textData.put("createdAt", savedTextContent.getCreatedAt().toString());

            log.info("Text generation completed and saved to database with ID: {} for image: {}",
                    savedTextContent.getId(), request.getImageId());

            Map<String, Object> response = createSuccessResponse("文案生成完成");
            response.put("data", textData);
            response.put("imageId", request.getImageId());
            response.put("contentType", request.getContentType());
            response.put("styleType", request.getStyleType());
            response.put("message", "文案生成成功");

            return ResponseEntity.ok(response);

        } catch (IllegalArgumentException e) {
            log.warn("Invalid parameter in text generation request: {}", e.getMessage());
            return ResponseEntity.badRequest().body(createErrorResponse("参数错误: " + e.getMessage()));
        } catch (Exception e) {
            log.error("Text generation failed for imageId: {}", request.getImageId(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("文案生成服务暂时不可用，请稍后重试"));
        }
    }

    /**
     * 获取图片的文案生成历史
     * @author wangguiyou
     * @param imageId 图片ID
     * @return 文案历史列表
     */
    @GetMapping("/text/history/{imageId}")
    public ResponseEntity<Map<String, Object>> getTextHistory(@PathVariable Long imageId) {
        log.info("Getting text history for image: {}", imageId);

        try {
            // 由于TextGenService不存储历史记录，返回空列表
            List<Map<String, Object>> emptyHistory = new java.util.ArrayList<>();

            Map<String, Object> response = createSuccessResponse("获取图片文案历史成功");
            response.put("data", emptyHistory);
            response.put("imageId", imageId);
            response.put("count", 0);
            response.put("message", "TextGenService不支持历史记录存储");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Get text history failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 删除生成的文案
     * @author wangguiyou
     * @param textId 文案ID
     * @return 删除结果
     */
    @DeleteMapping("/text/{textId}")
    public ResponseEntity<Map<String, Object>> deleteText(@PathVariable Long textId) {
        log.info("Deleting text content: {}", textId);

        try {
            // TextGenService不支持文案存储，无需删除操作
            Map<String, Object> response = createSuccessResponse("删除操作完成");
            response.put("textId", textId);
            response.put("message", "TextGenService不支持文案存储，无需删除");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Delete text content failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 更新文案内容
     * @author wangguiyou
     * @param textId 文案ID
     * @param request 更新请求
     * @return 更新结果
     */
    @PutMapping("/text/{textId}")
    public ResponseEntity<Map<String, Object>> updateText(@PathVariable Long textId, @RequestBody Map<String, String> request) {
        log.info("Updating text content: {}", textId);

        try {
            String content = request.get("content");

            // TextGenService不支持文案存储，返回模拟的更新结果
            Map<String, Object> updatedData = new HashMap<>();
            updatedData.put("id", textId);
            updatedData.put("content", content);
            updatedData.put("status", "UPDATED");
            updatedData.put("updatedAt", java.time.LocalDateTime.now().toString());

            Map<String, Object> response = createSuccessResponse("更新操作完成");
            response.put("data", updatedData);
            response.put("message", "TextGenService不支持文案存储，返回模拟结果");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Update text content failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 获取文案生成统计信息
     * @author wangguiyou
     * @return 统计信息
     */
    @GetMapping("/text/statistics")
    public ResponseEntity<Map<String, Object>> getTextStatistics() {
        log.info("Getting text generation statistics");

        try {
            // TextGenService不支持统计信息，返回模拟数据
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalContents", 0L);
            stats.put("successCount", 0L);
            stats.put("failedCount", 0L);
            stats.put("pendingCount", 0L);
            stats.put("successRate", 0.0);
            stats.put("message", "TextGenService不支持统计信息存储");

            Map<String, Object> response = createSuccessResponse("获取文案生成统计信息成功");
            response.put("data", stats);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Get text generation statistics failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 直接生成文案（用于测试）
     */
    @PostMapping("/generate-text/url")
    public ResponseEntity<Map<String, Object>> generateTextForUrl(@RequestBody Map<String, String> request) {
        String imageUrl = request.get("imageUrl");
        String contentType = request.getOrDefault("contentType", "SHORT");
        String styleType = request.getOrDefault("styleType", "PROMOTIONAL");
        String customPrompt = request.get("customPrompt");

        log.info("Direct text generation request for URL: {}, type: {}, style: {}", imageUrl, contentType, styleType);

        try {
            AIService.TextGenerationResult result = aiService.generateText(imageUrl, contentType, styleType, customPrompt);

            Map<String, Object> response = createSuccessResponse("图片URL文案生成完成");
            response.put("data", result);
            response.put("imageUrl", imageUrl);
            response.put("contentType", contentType);
            response.put("styleType", styleType);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Direct URL text generation failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 直接生成相似图片（用于测试）
     */
    @PostMapping("/generate-image/url")
    public ResponseEntity<Map<String, Object>> generateImageForUrl(@RequestBody Map<String, Object> request) {
        String imageUrl = (String) request.get("imageUrl");
        int count = (Integer) request.getOrDefault("count", 3);
        String style = (String) request.getOrDefault("style", "auto");
        String customPrompt = (String) request.get("customPrompt");

        log.info("Direct image generation request for URL: {}, count: {}, style: {}", imageUrl, count, style);

        try {
            AIService.ImageGenerationResult result = aiService.generateSimilarImages(imageUrl, count, style, customPrompt);

            Map<String, Object> response = createSuccessResponse("图片URL相似图片生成完成");
            response.put("data", result);
            response.put("imageUrl", imageUrl);
            response.put("count", count);
            response.put("style", style);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Direct URL image generation failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    /**
     * 创建成功响应
     */
    private Map<String, Object> createSuccessResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", message);
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }

    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }

    /**
     * 判断是否为限流错误
     * @author wangguiyou
     */
    private boolean isThrottlingError(Exception e) {
        String message = e.getMessage();
        return message != null && (
            message.contains("ServiceUnavailable") ||
            message.contains("Throttling") ||
            message.contains("Too many requests") ||
            message.contains("throttled") ||
            message.contains("capacity limits") ||
            message.contains("服务繁忙") ||
            message.contains("系统容量限制")
        );
    }

    /**
     * 获取详细的错误信息
     * @author wangguiyou
     */
    private String getDetailedErrorMessage(Exception e) {
        String message = e.getMessage();

        if (message == null) {
            return "图片分析失败，请稍后重试";
        }

        // 限流相关错误
        if (isThrottlingError(e)) {
            return "服务繁忙，请稍后重试。系统已自动进行重试机制。";
        }

        // API Key相关错误
        if (message.contains("API Key") || message.contains("Unauthorized")) {
            return "AI服务配置错误，请联系管理员";
        }

        // 余额不足
        if (message.contains("余额不足") || message.contains("InsufficientBalance")) {
            return "AI服务余额不足，请联系管理员";
        }

        // 参数错误
        if (message.contains("参数无效") || message.contains("InvalidParameter")) {
            return "图片格式不支持或参数错误，请检查图片格式";
        }

        // 模型错误
        if (message.contains("模型不存在") || message.contains("ModelNotFound")) {
            return "AI模型配置错误，请联系管理员";
        }

        // 默认错误信息
        return "图片分析失败: " + message;
    }

    /**
     * 转换为DTO
     * @author wangguiyou
     * @param textContent 文案实体
     * @return DTO对象
     */
    private TextContentDTO convertToDTO(TextContent textContent) {
        TextContentDTO dto = new TextContentDTO();
        dto.setId(textContent.getId());
        dto.setImageId(textContent.getImage().getId());
        dto.setContent(textContent.getContent());
        dto.setContentType(textContent.getContentType());
        dto.setStyleType(textContent.getStyleType());
        dto.setAiGenerationStatus(textContent.getAiGenerationStatus());
        dto.setCreatedAt(textContent.getCreatedAt());
        dto.setUpdatedAt(textContent.getUpdatedAt());
        return dto;
    }

    /**
     * 验证文案生成请求参数
     * @author wangguiyou
     * @param request 请求对象
     * @throws IllegalArgumentException 参数验证失败时抛出
     */
    private void validateTextGenerationRequest(TextGenerationRequest request) {
        if (request == null) {
            throw new IllegalArgumentException("请求参数不能为空");
        }

        if (request.getImageId() == null || request.getImageId() <= 0) {
            throw new IllegalArgumentException("图片ID不能为空且必须大于0");
        }

        if (request.getContentType() == null || request.getContentType().trim().isEmpty()) {
            throw new IllegalArgumentException("文案类型不能为空");
        }

        if (request.getStyleType() == null || request.getStyleType().trim().isEmpty()) {
            throw new IllegalArgumentException("文案风格不能为空");
        }

        // 验证枚举值
        try {
            TextContent.ContentType.valueOf(request.getContentType().toUpperCase());
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("无效的文案类型，支持的类型: SHORT, LONG");
        }

        try {
            TextContent.StyleType.valueOf(request.getStyleType().toUpperCase());
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("无效的文案风格，支持的风格: PROMOTIONAL, WARM, PROFESSIONAL");
        }

        // 自定义提示词长度验证
        if (request.getCustomPrompt() != null && request.getCustomPrompt().length() > 500) {
            throw new IllegalArgumentException("自定义提示词长度不能超过500个字符");
        }
    }

    /**
     * 文案生成请求
     * @author wangguiyou
     */
    public static class TextGenerationRequest {
        private Long imageId;
        private String contentType;
        private String styleType;
        private String customPrompt;

        // Getters and Setters
        public Long getImageId() { return imageId; }
        public void setImageId(Long imageId) { this.imageId = imageId; }

        public String getContentType() { return contentType; }
        public void setContentType(String contentType) { this.contentType = contentType; }

        public String getStyleType() { return styleType; }
        public void setStyleType(String styleType) { this.styleType = styleType; }

        public String getCustomPrompt() { return customPrompt; }
        public void setCustomPrompt(String customPrompt) { this.customPrompt = customPrompt; }

        @Override
        public String toString() {
            return "TextGenerationRequest{" +
                    "imageId=" + imageId +
                    ", contentType='" + contentType + '\'' +
                    ", styleType='" + styleType + '\'' +
                    ", customPrompt='" + (customPrompt != null ? "[PROVIDED]" : "[EMPTY]") + '\'' +
                    '}';
        }
    }

    /**
     * 图片分析请求
     * @author wangguiyou
     */
    public static class ImageAnalysisRequest {
        private Long imageId;
        private String customPrompt;

        // Getters and Setters
        public Long getImageId() { return imageId; }
        public void setImageId(Long imageId) { this.imageId = imageId; }

        public String getCustomPrompt() { return customPrompt; }
        public void setCustomPrompt(String customPrompt) { this.customPrompt = customPrompt; }
    }
}
